import emojimap from './emojimap.js'
var emoji = emojimap.emojiList.emoji

const formatTime = date => {
    const year = date.getFullYear()
    const month = date.getMonth() + 1
    const day = date.getDate()
    const hour = date.getHours()
    const minute = date.getMinutes()
    const second = date.getSeconds()

    return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}

const formatDate = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  return [year, month, day].map(formatNumber).join('.');
}

const formatNumber = n => {
    n = n.toString()
    return n[1] ? n : '0' + n
}

const formatAmount = amount => {
    let num;
    if (amount >= 1000 && amount < 10000) {
        num = amount / 1000;
        num = (Math.floor(num * 10) / 10) + "K";
    }
    else if (amount >= 10000) {
        num = amount / 10000;
        num = (Math.floor(num * 10) / 10) + "W";
    }else{
        return amount;
    }
    return num;
}

const aCity = {
    11: "北京",
    12: "天津",
    13: "河北",
    14: "山西",
    15: "内蒙古",
    21: "辽宁",
    22: "吉林",
    23: "黑龙江",
    31: "上海",
    32: "江苏",
    33: "浙江",
    34: "安徽",
    35: "福建",
    36: "江西",
    37: "山东",
    41: "河南",
    42: "湖北",
    43: "湖南",
    44: "广东",
    45: "广西",
    46: "海南",
    50: "重庆",
    51: "四川",
    52: "贵州",
    53: "云南",
    54: "西藏",
    61: "陕西",
    62: "甘肃",
    63: "青海",
    64: "宁夏",
    65: "新疆",
    71: "台湾",
    81: "香港",
    82: "澳门",
    91: "国外"
}

function isCardID(sId) {
    let iSum = 0;
    let info = "";
    if (!/^\d{17}(\d|x)$/i.test(sId)) return "你输入的身份证长度或格式错误";
    sId = sId.replace(/x$/i, "a");
    if (aCity[parseInt(sId.substr(0, 2))] == null) return "你的身份证地区非法";
    let sBirthday = sId.substr(6, 4) + "-" + Number(sId.substr(10, 2)) + "-" + Number(sId.substr(12, 2));
    let d = new Date(sBirthday.replace(/-/g, "/"));
    if (sBirthday != (d.getFullYear() + "-" + (d.getMonth() + 1) + "-" + d.getDate())) return "身份证上的出生日期非法";
    for (let i = 17; i >= 0; i--) iSum += (Math.pow(2, i) % 11) * parseInt(sId.charAt(17 - i), 11);
    if (iSum % 11 != 1) return "你输入的身份证号非法";
    return true;
}
function calcTimeHeader(time) {
    // 格式化传入时间
    let date = new Date(parseInt(time)),
        year = date.getUTCFullYear(),
        month = date.getUTCMonth(),
        day = date.getDate(),
        hour = date.getHours(),
        minute = date.getUTCMinutes()
    // 获取当前时间
    let currentDate = new Date(),
        currentYear = date.getUTCFullYear(),
        currentMonth = date.getUTCMonth(),
        currentDay = currentDate.getDate()
    // 计算是否是同一天
    if (currentYear == year && currentMonth == month && currentDay == day) {//同一天直接返回
        if (hour > 12) {
            return `下午 ${hour}:${minute < 10 ? '0' + minute : minute}`
        } else {
            return `上午 ${hour}:${minute < 10 ? '0' + minute : minute}`
        }
    }
    // 计算是否是昨天
    let yesterday = new Date(currentDate - 24 * 3600 * 1000)
    if (year == yesterday.getUTCFullYear() && month == yesterday.getUTCMonth && day == yesterday.getDate()) {//昨天
        return `昨天 ${hour}:${minute < 10 ? '0' + minute : minute}`
    } else {
        return `${year}-${month + 1}-${day} ${hour}:${minute < 10 ? '0' + minute : minute}`
    }
}
/**
 * 封装toast
 */
function showToast(type, text, obj) {
    let param = { duration: (obj && obj.duration) || 1500, mask: (obj && obj.isMask) || false }
    switch (type) {
        case 'text': {
            param['title'] = text || ''
            param['icon'] = 'none'
            break
        }
        case 'loading': {
            param['title'] = text || ''
            param['icon'] = 'loading'
            break
        }
        case 'success': {
            param['title'] = text || ''
            param['icon'] = 'success'
            break
        }
        case 'error': {
            param['title'] = text || ''
            param['image'] = '/images/emoji.png'
            break
        }
        default: {
            break
        }
    }
    wx.showToast(param)
}
/**
 * 输出猜拳图片对象，用于生成富文本图片节点
 */
function generateFingerGuessImageFile(value) {
    let file = { w: 50, h: 50, url: '' }
    switch (value) {
        case 1:
            file.url = 'http://yx-web.nos.netease.com/webdoc/h5/im/play-1.png'
            break
        case 2:
            file.url = 'http://yx-web.nos.netease.com/webdoc/h5/im/play-2.png'
            break
        case 3:
            file.url = 'http://yx-web.nos.netease.com/webdoc/h5/im/play-3.png'
            break
        default:
            break
    }
    return file
}
function generateBigEmojiImageFile(content) {
    let prefix = 'http://yx-web.nosdn.127.net/webdoc/h5/emoji/'
    let file = { w: 100, h: 100, url: '' }
    file.url = `${prefix}${content.data.catalog}/${content.data.chartlet}.png`
    return file
}
/**
 * 生成富文本节点
 */
function generateRichTextNode(text) {
    let tempStr = text
    let richTextNode = []
    let leftBracketIndex = tempStr.indexOf('[')
    let rightBracketIndex = tempStr.indexOf(']')
    let countOfWord = 0
    Array.from(tempStr).map(item => {
        if (item != '[' && item != ']') {
            countOfWord++
        }
    })
    if (leftBracketIndex == -1 || rightBracketIndex == -1 || countOfWord == 0) {//没有emoji
        richTextNode.push({
            type: 'text',
            text: tempStr
        })
        return richTextNode
    }
    while (tempStr.length != 0) {
        leftBracketIndex = tempStr.indexOf('[')
        rightBracketIndex = tempStr.indexOf(']')
        if (leftBracketIndex == 0) { // 开头是[
            rightBracketIndex = tempStr.indexOf(']')
            if (rightBracketIndex == -1) {
                richTextNode.push({
                    type: 'text',
                    text: tempStr
                })
                tempStr = ''
            } else {
                let emojiName = tempStr.slice(0, rightBracketIndex + 1)
                if (emoji[emojiName]) { // 有效emoji
                    richTextNode.push({
                        name: 'img',
                        attrs: {
                            width: '30rpx',
                            height: '30rpx',
                            src: emoji[emojiName].img
                        }
                    })
                } else {//无效emoji
                    richTextNode.push({
                        type: 'text',
                        text: emojiName
                    })
                }
                tempStr = tempStr.substring(rightBracketIndex + 1, tempStr.length)
            }
        } else { // 开头不是[
            if (leftBracketIndex == -1) {// 最后全是文字
                richTextNode.push({
                    type: 'text',
                    text: tempStr.slice(0, tempStr.length)
                })
                tempStr = ''
            } else {
                richTextNode.push({
                    type: 'text',
                    text: tempStr.slice(0, leftBracketIndex)
                })
                tempStr = tempStr.substring(leftBracketIndex, tempStr.length + 1)
            }
        }
    }
    return richTextNode
}/**
 * 处理图片富文本节点
 */
function generateImageNode(file) {
    // console.log(file)
    let width = 0, height = 0
    if (file.w > 250) {
        width = 200
        height = file.h / (file.w / 200)
    } else {
        width = file.w
        height = file.h
    }
    let richTextNode = []
    richTextNode.push({
        name: 'img',
        attrs: {
            width: `${width}rpx`,
            height: `${height}rpx`,
            src: file.url
        }
    })
    return richTextNode
}
module.exports = {
    formatNumber,
    formatTime,
    isCardID:isCardID,
    formatDate:formatDate,
    formatAmount: formatAmount,
    calcTimeHeader,
    showToast,
    generateFingerGuessImageFile,
    generateBigEmojiImageFile,
    generateRichTextNode,
    generateImageNode
}